package java51.lesson0619;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class AddXml {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		SAXReader reader = new SAXReader();
		String s1 = null;
		String s2 = null;
		try {
			Document doc = reader.read(new File("products.xml"));
			Element root = doc.getRootElement();
			System.out.println("请输入新增加的商品号：");
			String sch = sc.next();
			System.out.println("请输入商品名：");
			String ename = sc.next();
			List<Element> list = doc.selectNodes("/shop/product");
			for (Element e : list) {
				s1 = e.selectSingleNode("itemno").getText();
				s2 = e.selectSingleNode("name").getText();
				if ((s1.equals(sch)) || (s2.equals(ename))) {
					System.out.println("商品号或商品名称重复，添加失败！");
					return;
				}
			}

			Element newb = root.addElement("product");
			Element eitemno = newb.addElement("itemno");
			eitemno.setText(sch);
			Element name = newb.addElement("name");
			name.setText(ename);

			System.out.println("请输入是否是打折商品 true/false:");
			newb.addAttribute("discount", sc.next());
			System.out.println("请输入厂商地址：");
			newb.addAttribute("factoryaddr", sc.next());

			System.out.println("请输入商品价格：");
			Element price = newb.addElement("price");
			price.setText(sc.next());
			System.out.println("请输入库存数：");
			Element stockcount = newb.addElement("stockcount");
			stockcount.setText(sc.next());
			System.out.println("请输入计价单位：");
			Element unit = newb.addElement("unit");
			unit.setText(sc.next());

			OutputFormat format = OutputFormat.createCompactFormat();
			format.setEncoding("utf-8");
			XMLWriter xm = new XMLWriter(new FileOutputStream("products.xml"), format);
			xm.write(doc);
			xm.close();
			System.out.println("新商品添加成功");
			return;

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
